# today.py
# ... (other imports remain the same)
import datetime
import time

# PyQt5 Imports
from PyQt5.QtCore import Qt, QTimer # Make sure QTimer is imported
from PyQt5.QtGui import QCursor, QFont
from PyQt5.QtWidgets import QVBoxLayout

# Siui Imports
from siui.components import (
    SiDenseHContainer,
    SiDenseVContainer,
    SiLabel,
    SiWidget,
    SiSimpleButton
)
from siui.core import Si, SiColor
from siui.gui import SiFont
from siui.core.globals import SiGlobal

# Project Specific Imports
from ...core import Task
from ...widgets import RectButtonWithIconAndDescription
from .Mcdtw import select_standard_video, choose_existing_standard_video, select_comparison_video

# --- TaskIndicator, TaskIndicatorContainer, DateDisplay, TaskSelector, TaskDisplay ---
# --- DataItem, TodayTasksTimeLine, TodayDataTop, TodayDataBottom ---
# --- ComparisonDialog ---
# (Keep all these classes as they were in the previous correct version)
class TaskIndicator(SiLabel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.padding_top = 0
        self.time_stamp = 0

        self.indicator = SiLabel(self)
        self.indicator.setFixedSize(8, 20)
        self.indicator.setFixedStyleSheet("border-radius: 4px")
        self.indicator.setColor(self.getColor(SiColor.PROGRESS_BAR_PROCESSING))
        self.indicator.move(0, 0)

    def setTimeStamp(self, time_stamp):
        self.time_stamp = time_stamp

    def timeStamp(self):
        return self.time_stamp

    def setColor(self, color_code):
        self.indicator.setColor(color_code)

    def setPadding(self, padding_top):
        self.padding_top = padding_top
        self.resize(self.size())

    def enterEvent(self, a0):
        super().enterEvent(a0)
        # Defensive check for parent existence
        parent_widget = self.parent()
        if parent_widget:
            grandparent_widget = parent_widget.parent()
            if grandparent_widget and hasattr(grandparent_widget, 'setTracking') and hasattr(grandparent_widget, 'task_selector'):
                grandparent_widget.setTracking(False)
                grandparent_widget.task_selector.moveTo(self.x(), 0)

    def leaveEvent(self, a0):
        super().leaveEvent(a0)
        # Defensive check for parent existence
        parent_widget = self.parent()
        if parent_widget:
            grandparent_widget = parent_widget.parent()
            if grandparent_widget and hasattr(grandparent_widget, 'setTracking'):
                 grandparent_widget.setTracking(True)


    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.indicator.move((event.size().width() - self.indicator.width()) // 2, self.padding_top)


class TaskIndicatorContainer(SiWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.indicators = []


    def addTask(self, task: Task):
        # Defensive check: Ensure due_time_stamp is valid before proceeding
        if not isinstance(task.due_time_stamp, (int, float)) or task.due_time_stamp <= 0:
            print(f"Warning: Invalid timestamp for task '{task.name}'. Skipping.")
            return # Skip adding task with invalid timestamp

        try:
            d = datetime.datetime.fromtimestamp(task.due_time_stamp)
            now_ts = time.time()
            r = d - datetime.datetime.fromtimestamp(now_ts) # Calculate remaining time

            # Ensure remaining time calculation handles past due dates gracefully
            remaining_seconds = max(0, r.total_seconds()) # Don't show negative time remaining

            dim_color = SiColor.mix(self.getColor(SiColor.TEXT_B), task.color)

            new_task = TaskIndicator(self)
            new_task.setFixedStyleSheet("border-radius: 4px")
            new_task.setFixedWidth(20)
            new_task.setColor(task.color)
            new_task.setTimeStamp(task.due_time_stamp)

            new_task.setHint(
                f'<span style="color: {task.color}"><strong>{task.name}</strong></span><br>'
                f"{task.description}<p>"
                f'<span style="color: {dim_color}">截止时间：</span>{d.hour:02d}h {d.minute:02d}m<br>'
                f'<span style="color: {dim_color}">剩余时间：</span>{int(remaining_seconds // 3600):02d}h {int((remaining_seconds % 3600) // 60):02d}m'
            )

            self.indicators.append(new_task)
        except (OSError, OverflowError, ValueError) as e:
             print(f"Error creating datetime from timestamp {task.due_time_stamp} for task '{task.name}': {e}")
             # Optionally skip adding the task or handle differently


    def setPadding(self, padding):
        for indicator in self.indicators:
            indicator.setPadding(padding)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        try:
            td_timestamp = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
            total_seconds_today = 24 * 60 * 60

            for indicator in self.indicators:
                 # Clamp percentage between 0 and 1 to prevent positioning outside bounds
                 percentage = max(0.0, min(1.0, (indicator.timeStamp() - td_timestamp) / total_seconds_today))
                 x = int((self.width() - indicator.width()) * percentage)
                 indicator.setGeometry(x, 0, indicator.width(), event.size().height())
        except Exception as e:
             print(f"Error during resizeEvent in TaskIndicatorContainer: {e}") # Log potential errors


class DateDisplay(SiWidget): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.debug = SiLabel(self)
        self.debug.resize(196, 196)
        self.setCenterWidget(self.debug)

        self.month_widget = SiWidget(self)
        self.month_label = SiLabel(self.month_widget)
        self.month_mask = SiLabel(self.month_widget)

        self.date_widget = SiWidget(self)
        self.date_label = SiLabel(self.date_widget)

        self.month_label.setFont(SiFont.getFont(size=64, weight=QFont.Weight.Light, italic=True))
        self.date_label.setFont(SiFont.getFont(size=64, weight=QFont.Weight.Bold, italic=False))

        self.month_label.setTextColor(self.getColor(SiColor.TEXT_D))
        self.date_label.setTextColor(self.getColor(SiColor.TEXT_B))

        self.month_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.date_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)

        self.month_label.setFixedSize(128, 56)
        self.date_label.setFixedSize(128, 56)

        self.month_widget.move(-8, 50)
        self.date_widget.move(82, 50 + 27)

    def setMonthAndDate(self, month, date):
        self.month_label.setText(f"{month:02d} ")
        self.date_label.setText(f"{date:02d}")


class TaskSelector(SiLabel): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.padding_top = 10
        self.margin_top = 0

        self.stick_up = SiLabel(self)
        self.stick_down = SiLabel(self)

        self.stick_up.setFixedStyleSheet("border-radius: 1px")
        self.stick_down.setFixedStyleSheet("border-radius: 1px")

        self.stick_up.setColor(self.getColor(SiColor.TEXT_B))
        self.stick_down.setColor(self.getColor(SiColor.TEXT_B))

        self.selector = SiLabel(self)
        self.selector.resize(20, 32)

        self.selector.hide()
        self.stick_up.setFixedWidth(2)
        self.stick_down.setFixedWidth(2)

    def reloadStyleSheet(self):
        super().reloadStyleSheet()
        self.selector.setStyleSheet(
            "border-radius: 8px;"
            f"border: 3px solid {self.getColor(SiColor.TEXT_B)}"
        )

    def setPadding(self, padding):
        self.padding_top = padding
        self.resize(self.size())

    def setMarginTop(self, margin):
        self.margin_top = margin
        self.resize(self.size())

    def resizeEvent(self, event):
        super().resizeEvent(event)
        w, h = event.size().width(), event.size().height()

        # Ensure stick heights are non-negative
        stick_up_height = max(0, self.padding_top - self.margin_top)
        selector_height = self.selector.height() # Assume selector height is fixed or correctly set
        stick_down_start_y = self.margin_top + stick_up_height + selector_height
        stick_down_height = max(0, h - stick_down_start_y - self.margin_top) # Avoid negative height


        self.stick_up.setGeometry((w - self.stick_up.width()) // 2,
                                  self.margin_top,
                                  self.stick_up.width(),
                                  stick_up_height)

        self.stick_down.setGeometry((w - self.stick_up.width()) // 2,
                                    stick_down_start_y,
                                    self.stick_down.width(),
                                    stick_down_height)

        # Ensure selector is positioned correctly even if stick_up_height is 0
        self.selector.move(0, self.margin_top + stick_up_height)


class TaskDisplay(SiWidget): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.enabled_tracking = True
        self.setMouseTracking(True)

        self.task_track = SiLabel(self)
        self.task_track.setFixedStyleSheet("border-radius: 2px")
        self.task_track.setColor(self.getColor(SiColor.INTERFACE_BG_E))
        self.task_track.setFixedHeight(4)

        self.task_selector = TaskSelector(self)
        self.task_selector.setFixedWidth(20)
        self.task_selector.setMarginTop(0)
        self.task_selector.setOpacity(0)

        self.current_time_selector = TaskSelector(self)
        self.current_time_selector.setFixedWidth(20)
        self.current_time_selector.setMarginTop(12)
        self.current_time_selector.setOpacity(1)

        self.task_indicator_container = TaskIndicatorContainer(self)

        # --- Example Tasks (Consider loading real tasks) ---
        try:
             import random # Make sure random is imported if used here
             task_time1 = time.time() + 10000 + random.uniform(0, 1) # Add small random offset
             task_time2 = time.time() - 20000 + random.uniform(0, 1) # Add small random offset

             color1 = self.getColor(SiColor.PROGRESS_BAR_COMPLETING)
             color2 = self.getColor(SiColor.PROGRESS_BAR_PROCESSING)

             if not color1: color1 = "#00FF00" # Default valid color
             if not color2: color2 = "#FFA500" # Default valid color

             new_task_data1 = Task("回家睡觉", "躺下来闭上眼，睡觉就行", task_time1, color1)
             new_task_data2 = Task("写作业", "不写作业怎么交作业呢", task_time2, color2)

             self.task_indicator_container.addTask(new_task_data1)
             self.task_indicator_container.addTask(new_task_data2)
        except Exception as e:
             print(f"Error creating example tasks: {e}") # Log potential errors during task creation

        self.mouse_tracking_timer = QTimer(self)
        self.mouse_tracking_timer.setInterval(1000 // 60) # ~16.67 ms for 60 FPS
        self.mouse_tracking_timer.timeout.connect(self.mouse_tracking)

        self.time_updating_timer = QTimer(self)
        self.time_updating_timer.setInterval(1000) # Update every second
        self.time_updating_timer.timeout.connect(self.time_updating)
        self.time_updating_timer.start()
        self.time_updating() # Initial update

    def setTracking(self, state):
        self.enabled_tracking = state

    def mouse_tracking(self):
        if self.enabled_tracking is False:
            return
        try:
             local_pos = self.mapFromGlobal(QCursor.pos())
             target_x = max(0, min(self.width() - self.task_selector.width(),
                              local_pos.x() - self.task_selector.width() // 2))
             self.task_selector.move(target_x, 0)
        except Exception as e:
             print(f"Error during mouse tracking: {e}")


    def time_updating(self):
        try:
            now = datetime.datetime.now()
            today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
            seconds_passed = (now - today_start).total_seconds()
            total_seconds_today = 24 * 60 * 60

            if total_seconds_today <= 0: return

            percentage_passed = max(0.0, min(1.0, seconds_passed / total_seconds_today))

            target_x = int((self.width() - self.current_time_selector.width()) * percentage_passed)
            target_x = max(0, min(self.width() - self.current_time_selector.width(), target_x))

            self.current_time_selector.move(target_x, 0)
        except Exception as e:
             print(f"Error during time updating: {e}")


    def resizeEvent(self, event):
        super().resizeEvent(event)
        y_float = event.size().height() * 0.618
        y = int(y_float)

        padding_val = max(0, y - 14)
        indicator_padding_val = max(0, y - 8)
        track_y = max(0, y)
        track_width = max(0, event.size().width() - 20)

        self.task_selector.resize(self.task_selector.width(), event.size().height())
        self.task_selector.setMoveLimits(0, 0, max(0, event.size().width() - self.task_selector.width()), 0)
        self.task_selector.setPadding(padding_val)

        self.current_time_selector.resize(self.current_time_selector.width(), event.size().height())
        self.current_time_selector.setPadding(padding_val)

        self.task_indicator_container.setPadding(indicator_padding_val)
        self.task_indicator_container.setGeometry(0, 0, event.size().width(), event.size().height())

        self.task_track.setGeometry(10, track_y, track_width, 4)

        self.time_updating()

    def enterEvent(self, a0):
        super().enterEvent(a0)
        self.task_selector.setOpacityTo(1)
        self.current_time_selector.setOpacityTo(0.2)
        if not self.mouse_tracking_timer.isActive():
            self.mouse_tracking_timer.start()


    def leaveEvent(self, a0):
        super().leaveEvent(a0)
        self.task_selector.setOpacityTo(0)
        self.current_time_selector.setOpacityTo(1)
        if self.mouse_tracking_timer.isActive():
            self.mouse_tracking_timer.stop()


class DataItem(SiDenseVContainer): # Unchanged
    def __init__(self, title, data, size_title, size_data, parent=None):
        super().__init__(parent)

        self.title = SiLabel(self)
        self.title.setFont(SiFont.getFont(size=size_title, weight=QFont.Weight.Normal))
        self.title.setTextColor(self.getColor(SiColor.TEXT_D))
        self.title.setSiliconWidgetFlag(Si.AdjustSizeOnTextChanged)
        self.title.setText(str(title))

        self.data = SiLabel(self)
        self.data.setFont(SiFont.getFont(size=size_data, weight=QFont.Weight.Light))
        self.data.setTextColor(self.getColor(SiColor.TEXT_B))
        self.data.setSiliconWidgetFlag(Si.AdjustSizeOnTextChanged)
        self.data.setText(str(data))

        self.setAlignment(Qt.AlignLeft)
        self.setSpacing(0)
        self.addWidget(self.title)
        self.addWidget(self.data)

    def load(self, title, data):
        self.title.setText(str(title))
        self.data.setText(str(data))


class TodayTasksTimeLine(SiWidget): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.month = 0
        self.date = 0

        self.task_display = TaskDisplay(self)
        self.task_display.resize(0, 120)

    def mouseMoveEvent(self, a0):
        super().mouseMoveEvent(a0)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        widget_height = max(0, event.size().height())
        task_display_height = self.task_display.height()
        half_remaining_height = max(0, (widget_height - task_display_height) // 2)
        task_display_width = max(0, event.size().width())

        self.task_display.setGeometry(
            0,
            half_remaining_height,
            task_display_width,
            task_display_height
        )


class TodayDataTop(SiDenseHContainer): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.data_date = DataItem("当前日期", "-", 14, 32, parent=self)
        self.data_time = DataItem("当前时间", "-", 14, 32, parent=self)
        self.data_remaining_tasks = DataItem("今天计划练习数", "-", 14, 32, parent=self)
        self.data_time.setFixedWidth(120)

        self.refresh_data()
        self.data_date.adjustSize()
        self.data_time.adjustSize()
        self.data_remaining_tasks.adjustSize()


        self.setSpacing(32)
        self.addWidget(self.data_date)
        self.addWidget(self.data_time)
        self.addWidget(self.data_remaining_tasks)

        self.refresh_timer = QTimer(self)
        self.refresh_timer.setInterval(500)
        self.refresh_timer.timeout.connect(self.refresh_data)
        self.refresh_timer.start()

    def refresh_data(self):
        try:
            now = datetime.datetime.now()
            self.data_date.load("当前日期", f"{now.year}.{now.month}.{now.day}")
            self.data_time.load("当前时间", f"{now.hour:02d}:{now.minute:02d}:{now.second:02d}")
            remaining_tasks_count = "2" # Example
            self.data_remaining_tasks.load("今天剩余训练计划", remaining_tasks_count)
        except Exception as e:
            print(f"Error refreshing top data: {e}")


class TodayDataBottom(SiDenseHContainer): # Unchanged
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.accumulate_tasks = DataItem("累计完成训练", "...", 12, 24, parent=self)
        self.accumulate_memos = DataItem("累计训练目标", "...", 12, 24, parent=self)
        self.accumulate_focus = DataItem("累计训练时长", "...", 12, 24, parent=self)

        self.setSpacing(32)
        self.addWidget(self.accumulate_tasks)
        self.addWidget(self.accumulate_memos)
        self.addPlaceholder(2, side="right")
        self.addWidget(self.accumulate_focus, side="right")

        self.refresh_timer = QTimer(self)
        self.refresh_timer.setInterval(5000)
        self.refresh_timer.timeout.connect(self.refresh_data)
        self.refresh_timer.start()
        self.refresh_data() # Initial load

    def refresh_data(self):
         try:
             completed_trainings = "114" # Example
             training_goals = "514" # Example
             total_training_hours = "1919h" # Example

             self.accumulate_tasks.load("累计完成训练", completed_trainings)
             self.accumulate_memos.load("累计训练目标", training_goals)
             self.accumulate_focus.load("累计训练时长", total_training_hours)
         except Exception as e:
             print(f"Error refreshing bottom data: {e}")


class ComparisonDialog(SiWidget): # Unchanged
    """A simple modal dialog to show after comparison starts."""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("开始处理")
        self.setFixedSize(450, 250) # Adjust size as needed
        self.setColor(self.getColor(SiColor.INTERFACE_BG_A))
        self.setFixedStyleSheet("border-radius: 8px;")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        title_label = SiLabel("视频处理中", self)
        title_label.setFont(SiFont.getFont(size=18, weight=QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignCenter)

        info_label = SiLabel(
            "正在处理您上传的视频并进行比较分析。\n"
            "这可能需要一些时间，请稍候...",
            self
        )
        info_label.setAlignment(Qt.AlignCenter)
        info_label.setWordWrap(True)
        info_label.setTextColor(self.getColor(SiColor.TEXT_C))

        close_button = SiSimpleButton("知道了", self)
        close_button.setFixedWidth(120)
        close_button.clicked.connect(self.close_dialog)

        layout.addWidget(title_label)
        layout.addWidget(info_label)
        layout.addStretch(1) # Push button to bottom
        layout.addWidget(close_button, alignment=Qt.AlignCenter)

        self.setLayout(layout)

    def close_dialog(self):
        try:
             if hasattr(SiGlobal, 'siui') and SiGlobal.siui and \
                hasattr(SiGlobal.siui, 'windows') and "MAIN_WINDOW" in SiGlobal.siui.windows and \
                hasattr(SiGlobal.siui.windows["MAIN_WINDOW"], 'layerModalDialog'):
                 SiGlobal.siui.windows["MAIN_WINDOW"].layerModalDialog()
                 print(dir(SiGlobal.siui.windows["MAIN_WINDOW"].layerModalDialog()))

             else:
                 print("Error: Cannot access SiGlobal modal layer to close dialog.")
                 self.deleteLater()
        except Exception as e:
             print(f"Exception while closing dialog: {e}")
             self.deleteLater()


# --- TodayOperation (Modified with QTimer.singleShot) ---
class TodayOperation(SiDenseVContainer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setSpacing(8)
        self.setAdjustWidgetsSize(True)

        self.new_task = RectButtonWithIconAndDescription("上传视频", "为我们提供素材", "ic_fluent_check_filled", parent=self)
        self.new_task.setFixedHeight(80)
        self.new_task.clicked.connect(self.on_standard_clicked)

        self.new_memo = RectButtonWithIconAndDescription("选择训练", "选择要训练的舞蹈", "ic_fluent_notebook_filled", parent=self)
        self.new_memo.setFixedHeight(80)
        self.new_memo.clicked.connect(self.on_existing_clicked)

        self.start_focusing = RectButtonWithIconAndDescription("开始训练", "提供您的舞蹈视频", "ic_fluent_timer_filled", parent=self)
        self.start_focusing.setFixedHeight(80)
        # Connect to the MODIFIED on_comparison_clicked
        self.start_focusing.clicked.connect(self.on_comparison_clicked)

        self.addWidget(self.start_focusing, side="bottom")
        self.addWidget(self.new_memo, side="bottom")
        self.addWidget(self.new_task, side="bottom")

    def on_standard_clicked(self):
        select_standard_video()

    def on_existing_clicked(self):
        choose_existing_standard_video()
        # Example showing another layer (optional)
        # try:
        #     if hasattr(SiGlobal, 'siui') and SiGlobal.siui and \
        #        hasattr(SiGlobal.siui, 'windows') and "MAIN_WINDOW" in SiGlobal.siui.windows and \
        #        hasattr(SiGlobal.siui.windows["MAIN_WINDOW"], 'layerLeftGlobalDrawer'):
        #         SiGlobal.siui.windows["MAIN_WINDOW"].layerLeftGlobalDrawer().showLayer()
        #     else:
        #         print("Error: Cannot access SiGlobal left drawer layer.")
        # except Exception as e:
        #      print(f"Exception showing left drawer: {e}")

    def on_comparison_clicked(self):
        """
        Handles the 'Start Training' button click.
        Shows a modal dialog, then waits 3 seconds (non-blocking)
        before proceeding.
        """
        print("--" * 10)
        print("Comparison process initiated. Showing modal dialog.")

        # --- Show the Modal Dialog ---
        try:
            if hasattr(SiGlobal, 'siui') and SiGlobal.siui and \
               hasattr(SiGlobal.siui, 'windows') and "MAIN_WINDOW" in SiGlobal.siui.windows and \
               hasattr(SiGlobal.siui.windows["MAIN_WINDOW"], 'layerModalDialog'):

                dialog_instance = ComparisonDialog()
                SiGlobal.siui.windows["MAIN_WINDOW"].layerModalDialog().setDialog(dialog_instance)
                print("Modal dialog should be visible now.")

                # --- Schedule next step after 3 seconds ---
                # Use QTimer.singleShot for a non-blocking delay
                # It will call self._proceed_after_delay after 3000ms
                QTimer.singleShot(3000, self._proceed_after_delay)
                print("Scheduled next step in 3 seconds.")

            else:
                print("Error: Cannot access SiGlobal modal layer. Dialog not shown, proceeding immediately.")
                # Fallback: If modal can't be shown, maybe proceed directly or show a different message
                self._proceed_after_delay() # Or handle differently

        except Exception as e:
            print(f"Exception occurred when trying to show modal dialog: {e}")
            # Decide how to handle error - maybe proceed anyway?
            QTimer.singleShot(3000, self._proceed_after_delay) # Or maybe not schedule if dialog fails


    def _proceed_after_delay(self):
        """
        This method is called by the QTimer after the 3-second delay.
        """
        print("3-second delay finished.")
        print("--" * 10)

        # --- Close the modal dialog (optional) ---
        # You might want to close the dialog now or keep it open
        # if the *actual* processing starts here.
        try:
            if hasattr(SiGlobal, 'siui') and SiGlobal.siui and \
               hasattr(SiGlobal.siui, 'windows') and "MAIN_WINDOW" in SiGlobal.siui.windows and \
               hasattr(SiGlobal.siui.windows["MAIN_WINDOW"], 'layerModalDialog'): # Check if dialog exists
                print("Closing modal dialog.")
                SiGlobal.siui.windows["MAIN_WINDOW"].layerModalDialog().hide()
                print(dir(SiGlobal.siui.windows["MAIN_WINDOW"].layerModalDialog()))
            else:
                 print("Modal dialog layer or dialog not found, cannot close.")
        except Exception as e:
            print(f"Exception occurred when trying to close modal dialog: {e}")

        # --- Start Actual Processing Here ---
        # Now you can call the functions that do the real work,
        # like video selection and analysis.
        # If these are long tasks, consider running them in a separate thread
        # and potentially showing a *different* progress indicator.
        print("Proceeding with next steps (e.g., actual video processing)...")
        # Example:
        # result = select_comparison_video()
        # if result:
        #     x1, y1, x2, y2, score, time_data, similarity = result
        #     # Update UI, plot data, etc. (potentially using signals/slots if threaded)
        #     # self.about_page.start_plot_data(time_data, similarity)
        #     # self.about_page.update_score(score)
        #     print(f"Processing finished. Score: {score}")
        # else:
        #     print("Video selection cancelled or failed.")


    def resizeEvent(self, event): # Unchanged
        super().resizeEvent(event)

    # def set_about_page(self, x): # Keep if needed
    #     self.about_page = x


# --- TodayMainWidget (Unchanged Structure, uses modified TodayOperation) ---
class TodayMainWidget(SiWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.today_data_top = TodayDataTop(self)
        self.today_data_top.adjustSize()

        self.today_tasks = TodayTasksTimeLine(self)
        self.today_tasks.setFixedHeight(129)

        self.today_data_bottom = TodayDataBottom(self)
        self.today_data_bottom.adjustSize()

        self.today_operation = TodayOperation(self)
        self.today_operation.setFixedWidth(240)

        self.adjustSize()


    def adjustSize(self):
         top_h = self.today_data_top.height()
         tasks_h = self.today_tasks.height()
         bottom_h = self.today_data_bottom.height()
         spacing = 8

         calculated_height = max(0, top_h + spacing + tasks_h + spacing + bottom_h)
         operation_h = self.today_operation.sizeHint().height() # Use sizeHint for dynamic height
         final_height = max(calculated_height, operation_h)

         current_width = self.width() if self.width() > 0 else 600
         self.resize(current_width, final_height)


    def resizeEvent(self, event):
        super().resizeEvent(event)
        op_width = self.today_operation.width()
        gap = op_width + 16
        main_area_width = max(0, event.size().width() - gap)
        op_x = max(0, event.size().width() - op_width)

        self.today_data_top.setGeometry(
            0, 0,
            main_area_width, self.today_data_top.height()
        )

        tasks_y = self.today_data_top.height() + 8
        self.today_tasks.setGeometry(
            0, tasks_y,
            main_area_width, self.today_tasks.height()
        )

        bottom_y = tasks_y + self.today_tasks.height() + 8
        self.today_data_bottom.setGeometry(
            0, bottom_y,
            main_area_width, self.today_data_bottom.height()
        )

        op_height = max(0, event.size().height())
        self.today_operation.setGeometry(
            op_x, 0,
            op_width, op_height
        )